﻿using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        [HttpGet]
        [AcceptVerbs("GET", "POST")]
        [ActionName("AllProducts")]//支持请求的URL为：api/products/allproducts使用自定义的webapi路由配置覆盖掉默认的路由配置，启用ActionName匹配
        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }//webapi默认的路由机制是根据HttpMethod来路由，通过HttpMethod和URL中包含的关键字来匹配对应的Action方法，比如GetAllProducts这个Action默认匹配GET api/products

        //[HttpGet]
        [AcceptVerbs("GET", "POST")]//设置Action支持的HttpMethod方法
        [ActionName("ProductById")]//支持请求的URL为：api/products/productbyid/1
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }

        [NonAction]//意味着即使有ActionName匹配了，也不把它当做Action方法处理，而是始终保持为单纯的方法使用
        public void GetSomeData()
        {

        }
    }
}
